package com.zmn.oms.zmn.business.impl.work.autoflow.state;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.cube.common.utils.CollectionUtil;
import com.zmn.oms.business.interfaces.es.OrderWorkEsBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderDistributeConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.constant.OrderTagConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.model.dto.work.autoflow.FlowDistributeDTO;
import com.zmn.oms.model.entity.detail.OrderDetail;
import com.zmn.oms.model.entity.tag.OrderTag;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.detail.OrderDetailService;
import com.zmn.oms.services.interfaces.tag.OrderTagService;
import com.zmn.oms.zmn.business.interfaces.work.autoflow.state.WorkAutoFlowBService;
import com.zmn.oms.zmn.business.interfaces.work.customwork.ZsDistributeWorkBService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 类描述：派单
 *
 * @author heciqi
 * @date 2019/10/28 20:06
 */
@Slf4j
@Service("flowDistributeBService")
public class FlowDistributeBServiceImpl<T> implements WorkAutoFlowBService<T> {

	@Autowired
	private ZsDistributeWorkBService zsDistributeWorkBService;
	@Autowired
	private OrderTagService orderTagService;
	@Autowired
	private OrderWorkEsBService orderWorkEsBService;

	@Autowired
	protected OrderDetailService orderDetailService;

	@Override
	public ResultDTO<T> condition(OrderWork orderWork) {

		// 待取消，不允许自动派单 （老版跟单）
		/*Integer waitCancelStatus = workTrackBService.getWaitCancelStatus(orderWork.getOrderId(), orderWork.getWorkId(), TrackConsts.TRACK_CONTENT_ID_USER_CANCEL);
		if (Objects.equals(waitCancelStatus, GlobalConsts.YES)) {
			zsDistributeWorkBService.saveNonDistributeOrderLog(null, orderWork, null, "用户取消申请，不可派单");
			return ResultDTO.fail("用户取消申请，不可操作");
		}*/

		//  待取消，不允许自动派单 （新版跟单）
		/*EsOrderWork esOrderWork = orderWorkListBService.findOrderWorkById(orderWork.getWorkId());
		if (Objects.nonNull(esOrderWork) && CollectionUtil.isNotNullOrEmpty(esOrderWork.getWorkTrackList())) {
			long count = esOrderWork.getWorkTrackList()
					.stream()
					.filter(esWorkTrack -> Objects.equals(esWorkTrack.getTrackType(), TrackConsts.TRACK_CONTENT_ID_USER_CANCEL))
					.filter(esWorkTrack -> Objects.equals(esWorkTrack.getTrackStatus(), TrackConsts.TRACK_STATUS_PENDING) || Objects.equals(esWorkTrack.getTrackStatus(), TrackConsts.TRACK_STATUS_PROCESSING))
					.count();
			if (count > 0) {
				zsDistributeWorkBService.saveNonDistributeOrderLog(null, orderWork, null, "用户取消申请，不可派单");
				return ResultDTO.fail("用户取消申请，不可操作");
			}
		}*/

		if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_COMPENSATE)) {
			return ResultDTO.fail("赔偿单不可操作");
		}

        if (!Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_ASSIGN)) {
            // 是否网格化派单
            boolean isGirdId = zsDistributeWorkBService.isGridDistribute(orderWork);
            if (isGirdId) {
                if (!Objects.equals(orderWork.getStatus(), OrderStatusConsts.WORK_STATUS_CONFIRM)) {
                    return ResultDTO.fail("未确认");
                }
            } else {
                return ResultDTO.fail("未分单");
            }
        }

        if (Objects.equals(orderWork.getGrabType(), GlobalConsts.YES)) {
            return ResultDTO.fail("抢单方式，不可操作");
        }

        // 高价值用户订单必须手动派单
        List<OrderTag> orderTagList = orderTagService.listOrderTagByOrderIdSrcMaster(orderWork.getOrderId(), orderWork.getWorkId());
        if (CollectionUtil.isNotNullOrEmpty(orderTagList)) {
            boolean highValueUser = orderTagList.stream()
                    .anyMatch(tag -> Objects.equals(tag.getTagId(), OrderTagConsts.USER_TAG_ID_HIGH_VALUE) || Objects.equals(tag.getTagId(), OrderTagConsts.TAG_ID_HIGH_VALUE_USER));
            if (highValueUser) {
				zsDistributeWorkBService.saveNonDistributeOrderLog(null, orderWork, null, "高价值用户订单必须手动派单");
                return ResultDTO.fail("高价值用户订单必须手动派单");
            }
        }
		// vVip用户 平台指派
		if (Objects.equals(orderWork.getDistributeWay(), OrderDistributeConsts.DISTRIBUTE_WAY_PLAT)) {
			OrderDetail orderDetail = orderDetailService.findOrderDetailByKey(orderWork.getOrderId());
			if (Objects.nonNull(orderDetail)) {
				if (Objects.equals(orderDetail.getVvip(), 2)) {
					zsDistributeWorkBService.saveNonDistributeOrderLog(null, orderWork, null, "VVIP用户订单必须手动派单");
					return ResultDTO.fail("VVIP用户订单必须手动派单");
				}
			}
		}

		// 如果是返修单自动派单，判断源单的返修单数量
//		if (Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_REWORK)) {
//			if (NumberUtil.isNotNullOrZero(orderWork.getOriginalId())) {
//				BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
//				queryBuilder.must(QueryBuilders.termQuery("originalId", orderWork.getOriginalId()));
//				queryBuilder.must(QueryBuilders.termQuery("type", OrderConsts.ORDER_TYPE_REWORK));
//				NativeSearchQuery searchQuery = new NativeSearchQuery(queryBuilder);
//				int number = orderWorkEsBService.countByQuery(searchQuery).intValue();
//				if (number > 2) {
//					zsDistributeWorkBService.saveNonDistributeOrderLog(null, orderWork, new Date(), "源单返修下单次数>2次，不自动派（需手动派单）");
//					return ResultDTO.fail("源单返修下单次数>2次，不自动派（需手动派单）");
//				}
//			}
//		}

		return ResultDTO.success(orderWork);
	}

	@Override
	public void execute(T t) {
		try {
			FlowDistributeDTO flowDistributeDTO = (FlowDistributeDTO) t;
			zsDistributeWorkBService.autoDistribute(flowDistributeDTO.getOrderWork(), flowDistributeDTO.getRecommendMasterId());
			// DistributedLock lock = DistributedLockUtils.build(String.format(LockConsts.LOCK_AUTO_DISTRIBUTE, flowDistributeDTO.getOrderWork().getWorkId())
			// 		, LockConsts.LOCK_VALID_TIME);
			// log.info("自动派单-开始[{}]-1", flowDistributeDTO.getOrderWork().getWorkId());
			// if (lock.tryLock()) {
			// 	log.info("自动派单-开始[{}]-2", flowDistributeDTO.getOrderWork().getWorkId());
			// 	zsDistributeWorkBService.autoDistribute(flowDistributeDTO.getOrderWork(), flowDistributeDTO.getRecommendMasterId());
			// }
		} catch (Exception e) {
			log.error("自动派单异常 {}", e);
		}
	}
}
